package br.com.amadeus.android.activities.course.material;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Vector;

import org.apache.http.client.ClientProtocolException;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import br.com.amadeus.android.activities.home.R;
import br.com.amadeus.android.adapters.LearningResourcesAdapter;
import br.com.amadeus.android.adapters.MyCoursesListAdapter;
import br.com.amadeus.android.business.FacadeAmadeusDroid;
import br.com.amadeus.android.entities.Config;
import br.com.amadeus.android.entities.Course;
import br.com.amadeus.android.entities.Resource;
import br.com.amadeus.android.util.AccessMaterial;
import br.com.amadeus.android.util.ConstantsAmadeusDroid;
import br.com.amadeus.android.util.RESTFileContent;

public class HomeResourceActivity extends Activity {

	protected static final String CATEGORIA = "curso";
	private ListView listView;
	private String urlAmadeus;
	ProgressThread progressThread;
	ProgressDialog progressDialog;
	static final int PROGRESS_DIALOG = 0;
	private Resource resource;
	private Config config;
	private int opcao;
	public boolean threadIsAlive = true; 

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case PROGRESS_DIALOG:
			this.progressDialog = new ProgressDialog(HomeResourceActivity.this);
			progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			progressDialog.setTitle("Amadeus");
			progressDialog.setMessage("Baixando arquivo, por favor aguarde...");
			progressDialog.setIndeterminate(false);
			progressDialog.setMax(100);
			return progressDialog;
		default:
			return null;
		}
	}

	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
		switch (id) {
		case PROGRESS_DIALOG:
			progressDialog.setProgress(0);
			progressThread = new ProgressThread(handler);
			progressThread.start();
		}
	}

	final Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			int total = msg.arg1;
			progressDialog.setProgress(total);
			if (total >= 100) {
				dismissDialog(PROGRESS_DIALOG);
				progressThread.setState(ProgressThread.STATE_DONE);
				threadIsAlive = false; 
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.amadeus_screen_resourceinfo);
		//video de libras
		ImageButton librasBt = (ImageButton)findViewById(R.id.botaoLibras8);
        librasBt.setOnClickListener(new OnClickListener() {
			
			public void onClick(View arg0) {
				Intent it = new Intent("ABRIR_LIBRAS");
				it.putExtra("video_libras", "HomeResource.wmv");
				startActivity(it);
				
			}
		});
		Bundle gotBasket = getIntent().getExtras();
		int course_id = gotBasket.getInt("course_id");

		Course course = FacadeAmadeusDroid.getInstance(this).getCourse(
				course_id);

		List<Resource> listResources = FacadeAmadeusDroid.getInstance(this)
				.getListResourcesByCourse(course_id);

		LearningResourcesAdapter lra = new LearningResourcesAdapter(this,
				listResources);

		this.listView = (ListView) findViewById(R.id.lvMyResources);
		this.listView.setAdapter(lra);

		TextView tv = (TextView) findViewById(R.id.tvResourceCourse);
		tv.setText("Recursos " + course.getName());

		config = FacadeAmadeusDroid.getInstance(this).getConfig();

		SharedPreferences getPrefs = PreferenceManager
				.getDefaultSharedPreferences(getBaseContext());
		String pref = getPrefs.getString("listPref", "1");
		opcao = Integer.parseInt(pref);

		this.listView.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> parent, View v, int posicao,
					long id) {

				switch (opcao) {
				case ConstantsAmadeusDroid.MODO_ONLINE:

					resource = (Resource) listView.getAdapter()
							.getItem(posicao);
					if (resource.getForum().getId() == 0) {
						if (resource.getExtension().equalsIgnoreCase("pdf")) {
							urlAmadeus = config.getAmadeus_url()
									+ ConstantsAmadeusDroid.HOST_MATERIAL_PDF;
							
						} else if (resource.getExtension().equalsIgnoreCase("mp3")) {
							urlAmadeus = config.getAmadeus_url()
									+ ConstantsAmadeusDroid.HOST_MATERIAL_MP3;
							
						} else if (resource.getExtension().equalsIgnoreCase("wav")) {
							urlAmadeus = config.getAmadeus_url()
									+ ConstantsAmadeusDroid.HOST_MATERIAL_WAV;
							
						} else if (resource.getExtension().equalsIgnoreCase("doc")) {
							urlAmadeus = config.getAmadeus_url() 
									+ ConstantsAmadeusDroid.HOST_MATERIAL_DOC;
							
						} else if (resource.getExtension().equalsIgnoreCase("docx")) {
							urlAmadeus = config.getAmadeus_url() 
							+ ConstantsAmadeusDroid.HOST_MATERIAL_DOCX;
							
						} else if (resource.getExtension().equalsIgnoreCase("ppt")) {
							urlAmadeus = config.getAmadeus_url() 
							+ ConstantsAmadeusDroid.HOST_MATERIAL_PPT;
							
						} else if (resource.getExtension().equalsIgnoreCase("pptx")) {
							urlAmadeus = config.getAmadeus_url() 
							+ ConstantsAmadeusDroid.HOST_MATERIAL_PPTX;
							
						} else if (resource.getExtension().equalsIgnoreCase("ppsx")) {
							urlAmadeus = config.getAmadeus_url() 
							+ ConstantsAmadeusDroid.HOST_MATERIAL_PPSX;
							
						} else if (resource.getExtension().equalsIgnoreCase("jpg") || 
								resource.getExtension().equalsIgnoreCase("jpeg")) {
							urlAmadeus = config.getAmadeus_url() 
							+ ConstantsAmadeusDroid.HOST_MATERIAL_JPG;
							
						} else if (resource.getExtension().equalsIgnoreCase("png")) {
							urlAmadeus = config.getAmadeus_url() 
							+ ConstantsAmadeusDroid.HOST_MATERIAL_PNG;
							
						}

						File file = new File("/sdcard"
								+ ConstantsAmadeusDroid.ROOT_ARCHIVES + "/"
								+ resource.getCompleteValue());
						if (!file.exists()) {
							showDialog(PROGRESS_DIALOG);
							
						} else {
							/*Toast.makeText(HomeResourceActivity.this,
									"O Recurso já foi baixado.",
									Toast.LENGTH_SHORT).show();*/
							try {
								loadDocInReader(file);
							} catch (ActivityNotFoundException e) {
								Log.e(CATEGORIA, e.getMessage(),e);
							} catch (Exception e) {
								Log.e(CATEGORIA, e.getMessage(),e);
							}
						}
					} else {
						Bundle basket = new Bundle();
						basket.putInt("forum_id", resource.getForum().getId());
						Intent it = new Intent("FORUM");
						it.putExtras(basket);
						startActivity(it);
					}

					break;

				case ConstantsAmadeusDroid.MODO_OFFLINE:

					resource = (Resource) listView.getAdapter()
							.getItem(posicao);
					if (resource.getForum().getId() == 0) {
						Toast.makeText(
								HomeResourceActivity.this,
								"Não é possível baixar o Recurso no Modo de Acesso offline.",
								Toast.LENGTH_SHORT).show();
					} else {
						Bundle basket = new Bundle();
						basket.putInt("forum_id", resource.getForum().getId());
						Intent it = new Intent("FORUM");
						it.putExtras(basket);
						startActivity(it);
					}

					break;
				}

			}
		});
	}
	
	// Metodo que abre o arquivos, independentemente dos tipos
	private void loadDocInReader(File file) throws ActivityNotFoundException, Exception {

		Uri path = Uri.fromFile(file);
		Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
		pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		if(file.getName().endsWith(".pdf") || file.getName().endsWith(".PDF"))
			pdfIntent.setDataAndType(path, "application/pdf");
		else if (file.getName().endsWith(".WAV") || file.getName().endsWith(".wav"))
			pdfIntent.setDataAndType(path, "audio/vnd.wave");
		else if(file.getName().endsWith(".MP3") || file.getName().endsWith(".mp3"))
			pdfIntent.setDataAndType(path, "audio/mpeg");
		else if(file.getName().endsWith(".DOC") || file.getName().endsWith(".doc"))
			pdfIntent.setDataAndType(path, "application/msword");
		else if(file.getName().endsWith(".DOCX") || file.getName().endsWith(".docx"))
			pdfIntent.setDataAndType(path, "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
		else if(file.getName().endsWith(".PPT") || file.getName().endsWith(".ppt"))
			pdfIntent.setDataAndType(path, "application/vnd.ms-powerpoint");
		else if(file.getName().endsWith(".PPTX") || file.getName().endsWith(".pptx"))
			pdfIntent.setDataAndType(path, "application/vnd.openxmlformats-officedocument.presentationml.presentation");
		else if(file.getName().endsWith(".PPSX") || file.getName().endsWith(".ppsx"))
			pdfIntent.setDataAndType(path, "application/vnd.openxmlformats-officedocument.presentationml.slideshow");
		else if(file.getName().endsWith(".JPG") || file.getName().endsWith(".jpg") || 
				file.getName().endsWith(".JPEG") || file.getName().endsWith(".jpeg"))
			pdfIntent.setDataAndType(path, "image/jpeg");
		else if(file.getName().endsWith(".PNG") || file.getName().endsWith(".png"))
			pdfIntent.setDataAndType(path, "image/png");
		if(pdfIntent.getType()!= null)
			startActivity(pdfIntent);
	}

	/** Nested class that performs progress calculations (counting) */
	private class ProgressThread extends Thread {
		Handler mHandler;
		final static int STATE_DONE = 0;
		final static int STATE_RUNNING = 1;
		int mState;
		int total;
		InputStream input;
		long lengthOfFile = 0;

		ByteArrayOutputStream baos = new ByteArrayOutputStream();

		ProgressThread(Handler h) {
			mHandler = h;
		}

		public void run() {
			mState = STATE_RUNNING;
			total = 0;
			File myFile = null;

			try {

				RESTFileContent rfc = new RESTFileContent();
				AccessMaterial material = AccessMaterial
						.getInstance(urlAmadeus);
				String address = material.getUrlAmadeus()
						+ resource.getAmadeus_id();

				Vector<Object> vector = rfc.getRestFileMaterial(address);
				String rsrc = (String) vector.get(0);
				this.lengthOfFile = rsrc.length();
				this.input = (InputStream) vector.get(1);

				byte data[] = new byte[512];
				int count = 0;

				while (mState == STATE_RUNNING) {
					while ((count = this.input.read(data)) > 0) {
						total += count;
						// publishing the progress....
						baos.write(data, 0, count);
						Message msg = mHandler.obtainMessage();
						msg.arg1 = (int) (total * 100 / lengthOfFile);
						mHandler.sendMessage(msg);
					}

				}

				File root = Environment.getExternalStorageDirectory();
				String extStorageDirectory = Environment
						.getExternalStorageDirectory().toString();
				String rootArchive = extStorageDirectory
						+ ConstantsAmadeusDroid.ROOT_ARCHIVES;
				if (root.canWrite()) {
					myFile = new File(rootArchive,
							resource.getCompleteValue());
					FileOutputStream fOut = new FileOutputStream(myFile);

					fOut.write(baos.toByteArray());
					fOut.close();
				}

				baos.close();
				input.close();
				rsrc = null;
				System.gc();
				
				try {
					loadDocInReader(myFile);
				} catch (ActivityNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			} catch (ClientProtocolException e) {
				Log.e(CATEGORIA, e.getMessage(), e);
				dismissDialog(PROGRESS_DIALOG);
			} catch (IOException e) {
				Log.e(CATEGORIA, e.getMessage(), e);
				dismissDialog(PROGRESS_DIALOG);
			} catch(Exception e){
				Log.e(CATEGORIA, e.getMessage(), e);
			}

		}

		/*
		 * sets the current state for the thread, used to stop the thread
		 */
		public void setState(int state) {
			mState = state;
		}
	}

}
